package com.jianshuge.app.ui;

import java.util.ArrayList;
import java.util.List;

import com.jianshuge.app.AppContext;
import com.jianshuge.app.AppException;
import com.jianshuge.app.R;

import com.jianshuge.app.adapter.ListViewBooklistAdapter;
import com.jianshuge.app.adapter.ListViewBookAdapter;

import com.jianshuge.app.bean.Booklist;
import com.jianshuge.app.bean.BookItem;

import com.jianshuge.app.bean.BooklistList;
import com.jianshuge.app.bean.BookItemList;

import com.jianshuge.app.common.StringUtils;
import com.jianshuge.app.common.UIHelper;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Search extends BaseActivity{
	private Button mSearchBtn;
	private EditText mSearchEditer;
	private ProgressBar mProgressbar;
	
	private Button search_catalog_booklist;
	private Button search_catalog_book;
	
	private ListView mlvSearchBooklist;
	private List<Booklist> lvSearchBooklistData = new ArrayList<Booklist>();
	private ListViewBooklistAdapter lvSearchBooklistAdapter;
	private View lvSearchBooklist_footer;
	private TextView lvSearchBooklist_foot_more;
	private ProgressBar lvSearchBooklist_foot_progress;
    private Handler mSearchBooklistHandler;
    private int lvSearchBooklistSumData;
		
	private ListView mlvSearchBook;
	private List<BookItem> lvSearchBookData = new ArrayList<BookItem>();	
	private ListViewBookAdapter lvSearchBookAdapter;
	private View lvSearchBook_footer;
	private TextView lvSearchBook_foot_more;
	private ProgressBar lvSearchBook_foot_progress;
    private Handler mSearchBookHandler;
    private int lvSearchBookSumData;
	
	private int curSearchCatalog = BookItemList.CATALOG_BOOKLIST;
	private String curSearchContent = "";
    
	private InputMethodManager imm;
	
	private final static int DATA_LOAD_ING = 0x001;
	private final static int DATA_LOAD_COMPLETE = 0x002;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search);
        
        this.initView();
        
        this.initData();
	}
	
    /**
     * 头部按钮展示
     * @param type
     */
    private void headButtonSwitch(int type) {
    	switch (type) {
    	case DATA_LOAD_ING:
    		mSearchBtn.setClickable(false);
			mProgressbar.setVisibility(View.VISIBLE);
			break;
		case DATA_LOAD_COMPLETE:
			mSearchBtn.setClickable(true);
			mProgressbar.setVisibility(View.GONE);
			break;
		}
    }
	
	//初始化视图控件
    private void initView()
    {
    	imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    	
    	mSearchBtn = (Button)findViewById(R.id.search_btn);
    	mSearchEditer = (EditText)findViewById(R.id.search_editer);
    	mProgressbar = (ProgressBar)findViewById(R.id.search_progress);
    	
    	mSearchBtn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				mSearchEditer.clearFocus();
				curSearchContent = mSearchEditer.getText().toString();
				
				if( curSearchCatalog == 1)
					loadLvSearchBooklistData(curSearchCatalog, 0, mSearchBooklistHandler, UIHelper.LISTVIEW_ACTION_INIT);
				if( curSearchCatalog == 2)
					loadLvSearchBookData(curSearchCatalog, 0, mSearchBookHandler, UIHelper.LISTVIEW_ACTION_INIT);
				
			}
		});
    	
    	mSearchEditer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
			public void onFocusChange(View v, boolean hasFocus) {
				if(hasFocus){  
					imm.showSoftInput(v, 0);  
		        }  
		        else{  
		            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);  
		        }  
			}
		});
    	
    	mSearchEditer.setOnKeyListener(new View.OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH) {
					if(v.getTag() == null) {
						v.setTag(1);
						mSearchEditer.clearFocus();
						curSearchContent = mSearchEditer.getText().toString();
						
						if( curSearchCatalog == 1)
							loadLvSearchBooklistData(curSearchCatalog, 0, mSearchBooklistHandler, UIHelper.LISTVIEW_ACTION_INIT);
						if( curSearchCatalog == 2)
							loadLvSearchBookData(curSearchCatalog, 0, mSearchBookHandler, UIHelper.LISTVIEW_ACTION_INIT);
						
					}else{
						v.setTag(null);
					}
					return true;
				}
				return false;
			}
		});
    	
    	search_catalog_booklist = (Button)findViewById(R.id.search_catalog_booklist);
    	search_catalog_book = (Button)findViewById(R.id.search_catalog_book);

    	search_catalog_booklist.setOnClickListener(this.searchBtnClick(search_catalog_booklist,BookItemList.CATALOG_BOOKLIST));
    	search_catalog_book.setOnClickListener(this.searchBtnClick(search_catalog_book,BookItemList.CATALOG_BOOK));   	
    	search_catalog_booklist.setEnabled(false);
    	
    	initSearchBooklistListView();
    	initSearchBookListView();
    }
    
    private void initSearchBooklistListView() {
    	
    	lvSearchBooklist_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
    	lvSearchBooklist_foot_more = (TextView)lvSearchBooklist_footer.findViewById(R.id.listview_foot_more);
    	lvSearchBooklist_foot_progress = (ProgressBar)lvSearchBooklist_footer.findViewById(R.id.listview_foot_progress);
    	
    	lvSearchBooklistAdapter = new ListViewBooklistAdapter(this, BookItemList.CATALOG_BOOKLIST, lvSearchBooklistData, R.layout.booklist_listitem); 
    	mlvSearchBooklist = (ListView)findViewById(R.id.searchbooklist_listview);
    	mlvSearchBooklist.setVisibility(ListView.GONE);
    	mlvSearchBooklist.addFooterView(lvSearchBooklist_footer);
    	mlvSearchBooklist.setAdapter(lvSearchBooklistAdapter); 
    	
    	mlvSearchBooklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		//点击头部、底部栏无效
        		if(view == lvSearchBooklist_footer) 
        			return;
        		
        		Booklist booklist = null;
        		//判断是否是TextView
        		if (view instanceof TextView) {
					booklist = (Booklist) view.getTag();
				} else {
					TextView tv = (TextView) view.findViewById(R.id.booklist_listitem_title);
					booklist = (Booklist) tv.getTag();
				}
				if (booklist == null)
					return;

				// 跳转书单详情页
				UIHelper.showBooklistDetail(view.getContext(), booklist.getId());
        	}
		});
    	
    	mlvSearchBooklist.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {				
				//数据为空--不用继续下面代码了
				if(lvSearchBooklistData.size() == 0) return;
				
				//判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if(view.getPositionForView(lvSearchBooklist_footer) == view.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				int curLvDataState = StringUtils.toInt(mlvSearchBooklist.getTag());
				if(scrollEnd && curLvDataState==UIHelper.LISTVIEW_DATA_MORE)
				{
					mlvSearchBooklist.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					lvSearchBooklist_foot_more.setText(R.string.load_ing);
					lvSearchBooklist_foot_progress.setVisibility(View.VISIBLE);
					//当前pageIndex
					int pageIndex = lvSearchBooklistSumData / 10;
					loadLvSearchBooklistData(curSearchCatalog, pageIndex, mSearchBooklistHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}
			
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				
			}
		});
    	
    }
    
    private void initSearchBookListView() {
    	
    	lvSearchBook_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
    	lvSearchBook_foot_more = (TextView)lvSearchBook_footer.findViewById(R.id.listview_foot_more);
    	lvSearchBook_foot_progress = (ProgressBar)lvSearchBook_footer.findViewById(R.id.listview_foot_progress);
    	
    	lvSearchBookAdapter = new ListViewBookAdapter(this, lvSearchBookData, R.layout.book_listitem); 
    	
    	mlvSearchBook = (ListView)findViewById(R.id.searchbook_listview);
    	mlvSearchBook.setVisibility(ListView.GONE);
    	mlvSearchBook.addFooterView(lvSearchBook_footer);
    	mlvSearchBook.setAdapter(lvSearchBookAdapter); 
    	
    	mlvSearchBook.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        		//点击底部栏无效
        		if( view == lvSearchBook_footer ) 
        			return;
        		
        		BookItem book_item = null;
        		//判断是否是TextView
        		if(view instanceof TextView){
        			book_item = (BookItem)view.getTag();
        		}else{
        			TextView title = (TextView)view.findViewById(R.id.book_listitem_title);
        			book_item = (BookItem)title.getTag();
        		} 
        		if(book_item == null) return;
        		
         	//	UIHelper.showBookDetail(Search.this, book_item.getBookId());
        		UIHelper.showBookDetail(Search.this, book_item.getSubjectId());
        	}
		});
    	
    	mlvSearchBook.setOnScrollListener(new AbsListView.OnScrollListener() {
			public void onScrollStateChanged(AbsListView view, int scrollState) {				
				//数据为空--不用继续下面代码了
				if(lvSearchBookData.size() == 0) return;
				
				//判断是否滚动到底部
				boolean scrollEnd = false;
				try {
					if(view.getPositionForView(lvSearchBook_footer) == view.getLastVisiblePosition())
						scrollEnd = true;
				} catch (Exception e) {
					scrollEnd = false;
				}
				
				int curLvDataState = StringUtils.toInt(mlvSearchBook.getTag());
				if(scrollEnd && curLvDataState==UIHelper.LISTVIEW_DATA_MORE)
				{
					mlvSearchBook.setTag(UIHelper.LISTVIEW_DATA_LOADING);
					lvSearchBook_foot_more.setText(R.string.load_ing);
					lvSearchBook_foot_progress.setVisibility(View.VISIBLE);
					//当前pageIndex
					int pageIndex = lvSearchBookSumData / 10;
					loadLvSearchBookData(curSearchCatalog, pageIndex, mSearchBookHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
				}
			}
			public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
				
			}
		});
    }
    
    
    //初始化控件数据
  	private void initData() 
  	{			
		mSearchBooklistHandler = new Handler() {
			public void handleMessage(Message msg) {
				
				headButtonSwitch(DATA_LOAD_COMPLETE);

				if(msg.what >= 0){						
					BooklistList list = (BooklistList)msg.obj;

					switch (msg.arg1) {
					case UIHelper.LISTVIEW_ACTION_INIT:
					case UIHelper.LISTVIEW_ACTION_REFRESH:
					case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
						lvSearchBooklistSumData = msg.what;
						lvSearchBooklistData.clear();//先清除原有数据
						lvSearchBooklistData.addAll(list.getBooklistList());
						break;
					case UIHelper.LISTVIEW_ACTION_SCROLL:
						lvSearchBooklistSumData += msg.what;
						if(lvSearchBooklistData.size() > 0){
							for(Booklist booklist1 : list.getBooklistList()){
								boolean b = false;
								for(Booklist booklist2 : lvSearchBooklistData){
									if(booklist1.getId() == booklist2.getId()){
										b = true;
										break;
									}
								}
								if(!b) lvSearchBooklistData.add(booklist1);
							}
						}else{
							lvSearchBooklistData.addAll(list.getBooklistList());
						}
						break;
					}	
					
					if(msg.what < 10){
						mlvSearchBooklist.setTag(UIHelper.LISTVIEW_DATA_FULL);
						lvSearchBooklistAdapter.notifyDataSetChanged();
						lvSearchBooklist_foot_more.setText(R.string.load_full);
					}else if(msg.what == 10){					
						mlvSearchBooklist.setTag(UIHelper.LISTVIEW_DATA_MORE);
						lvSearchBooklistAdapter.notifyDataSetChanged();
						lvSearchBooklist_foot_more.setText(R.string.load_more);
					}
				}
				else if(msg.what == -1){
					//有异常--显示加载出错 & 弹出错误消息
					mlvSearchBooklist.setTag(UIHelper.LISTVIEW_DATA_MORE);
					lvSearchBooklist_foot_more.setText(R.string.load_error);
					((AppException)msg.obj).makeToast(Search.this);
				}
				if(lvSearchBooklistData.size()==0){
					mlvSearchBooklist.setTag(UIHelper.LISTVIEW_DATA_EMPTY);
					lvSearchBooklist_foot_more.setText(R.string.load_empty);
				}
				
				lvSearchBooklist_foot_progress.setVisibility(View.GONE);
				if(msg.arg1 != UIHelper.LISTVIEW_ACTION_SCROLL){
					mlvSearchBooklist.setSelection(0);//返回头部
				}
			}
		};
		
		
		mSearchBookHandler = new Handler() {
			public void handleMessage(Message msg) {
				
				headButtonSwitch(DATA_LOAD_COMPLETE);

				if(msg.what >= 0){						
					BookItemList list = (BookItemList)msg.obj;

					switch (msg.arg1) {
					case UIHelper.LISTVIEW_ACTION_INIT:
					case UIHelper.LISTVIEW_ACTION_REFRESH:
					case UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG:
						lvSearchBookSumData = msg.what;
						lvSearchBookData.clear();//先清除原有数据
						lvSearchBookData.addAll(list.getBookList());
						break;
					case UIHelper.LISTVIEW_ACTION_SCROLL:
						lvSearchBookSumData += msg.what;
						if(lvSearchBookData.size() > 0){
							for(BookItem bookitem1 : list.getBookList()){
								boolean b = false;
								for(BookItem bookitem2 : lvSearchBookData){
									if(bookitem1.getId() == bookitem2.getId()){
										b = true;
										break;
									}
								}
								if(!b) lvSearchBookData.add(bookitem1);
							}
						}else{
							lvSearchBookData.addAll(list.getBookList());
						}
						break;
					}	
					
					if(msg.what < 10){
						mlvSearchBook.setTag(UIHelper.LISTVIEW_DATA_FULL);
						lvSearchBookAdapter.notifyDataSetChanged();
						lvSearchBook_foot_more.setText(R.string.load_full);
					}else if(msg.what == 10){					
						mlvSearchBook.setTag(UIHelper.LISTVIEW_DATA_MORE);
						lvSearchBookAdapter.notifyDataSetChanged();
						lvSearchBook_foot_more.setText(R.string.load_more);
					}
				}
				else if(msg.what == -1){
					//有异常--显示加载出错 & 弹出错误消息
					mlvSearchBook.setTag(UIHelper.LISTVIEW_DATA_MORE);
					lvSearchBook_foot_more.setText(R.string.load_error);
					((AppException)msg.obj).makeToast(Search.this);
				}
				if(lvSearchBookData.size()==0){
					mlvSearchBook.setTag(UIHelper.LISTVIEW_DATA_EMPTY);
					lvSearchBook_foot_more.setText(R.string.load_empty);
				}
				lvSearchBook_foot_progress.setVisibility(View.GONE);
				if(msg.arg1 != UIHelper.LISTVIEW_ACTION_SCROLL){
					mlvSearchBook.setSelection(0);//返回头部
				}
			}
		};
		
  	}
  	
    /**
     * 线程加载书单数据
     * @param type 0:全部收藏 1:书单 2:书籍 
     * @param pageIndex 当前页数
     * @param handler 处理器
     * @param action 动作标识
     */
	private void loadLvSearchBooklistData(final int catalog,final int pageIndex,final Handler handler,final int action){  
		if(StringUtils.isEmpty(curSearchContent)){
			UIHelper.ToastMessage(Search.this, "请输入搜索内容");
			return;
		}
		
		headButtonSwitch(DATA_LOAD_ING);
		mlvSearchBook.setVisibility(ListView.GONE);
		mlvSearchBooklist.setVisibility(ListView.VISIBLE);
		
		
		new Thread(){
			public void run() {
				Message msg = new Message();
				try {
					BooklistList list = ((AppContext)getApplication()).SearchBooklist(catalog, curSearchContent, pageIndex, 10);
					msg.what = list.getPageSize();
					msg.obj = list;
	            } catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            }
				msg.arg1 = action;//告知handler当前action
				
				if(curSearchCatalog == catalog)
					handler.sendMessage(msg);
			}
		}.start();
	} 
	
	
	private void loadLvSearchBookData(final int catalog,final int pageIndex,final Handler handler,final int action){  
		
		if(StringUtils.isEmpty(curSearchContent)){
			UIHelper.ToastMessage(Search.this, "请输入搜索内容");
			return;
		}
		
		headButtonSwitch(DATA_LOAD_ING);
		mlvSearchBooklist.setVisibility(ListView.GONE);
		mlvSearchBook.setVisibility(ListView.VISIBLE);
		
		new Thread(){
			public void run() {
				Message msg = new Message();
				try {
					BookItemList book_item_list = ((AppContext)getApplication()).SearchBook(catalog, curSearchContent, pageIndex, 10);
					msg.what = book_item_list.getPageSize();
					msg.obj = book_item_list;
	            } catch (AppException e) {
	            	e.printStackTrace();
	            	msg.what = -1;
	            	msg.obj = e;
	            }
				msg.arg1 = action;//告知handler当前action
				if(curSearchCatalog == catalog)
					handler.sendMessage(msg);
			}
		}.start();
	} 
	
	private View.OnClickListener searchBtnClick(final Button btn,final int catalog){
    	return new View.OnClickListener() {
			public void onClick(View v) {
		    	if(btn == search_catalog_booklist)
		    		search_catalog_booklist.setEnabled(false);
		    	else
		    		search_catalog_booklist.setEnabled(true);
		    	
		    	if(btn == search_catalog_book)
		    		search_catalog_book.setEnabled(false);
		    	else
		    		search_catalog_book.setEnabled(true);	
				
				//开始搜索
				mSearchEditer.clearFocus();
				curSearchContent = mSearchEditer.getText().toString();
				curSearchCatalog = catalog;
				
				if( curSearchCatalog == 1)
					loadLvSearchBooklistData(curSearchCatalog, 0, mSearchBooklistHandler, UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);
				if( curSearchCatalog == 2)
					loadLvSearchBookData(curSearchCatalog, 0, mSearchBookHandler, UIHelper.LISTVIEW_ACTION_CHANGE_CATALOG);
		    	
			}
		};
    }
}
